<?php
class Zendvn_Recursive{
	
	private $_data;
	private $_filter;
	
 	public function __construct($data = null){
 		$this->_data = $data;
 		$this->_filter = new Zendvn_Filter_Filter();
 		$this->_cmsUrl = new Zendvn_View_Helper_CmsUrl();
 	}
	
 	public function process($parents = 0){
 		$newMenu = array();
 		$this->recursive($this->_data,$parents,1,$newMenu);
 		return $newMenu;
 	}
 	
	public function recursive($menu,$parents = 0,$level = 1,&$newMenu){
		foreach ($menu as $key => $val){
			if($val['parents'] == $parents){
				$val['level'] = $level;
				$newMenu[] = $val;
				unset($menu[$key]);
				$this->recursive($menu,$val['id'],$val['level'] + 1,$newMenu);
			}
		}
	}
	
	public function getParentsIdArray($id,$options = null){
		if($options['type'] == 1){
			$arrParents[] = $id;
		}
		$this->findParents($this->_data,$id, &$arrParents);
		return $arrParents;
	}
	
	public function findParents($sourceArr,$id, &$arrParents){
		foreach ($sourceArr as $key => $value){		
			if($value['id'] == $id){
				if( $value['parents'] >0 ){
					$arrParents[] = $value['parents'];
					unset($sourceArr[$key]);
					$newID = $value['parents'];
					$this->findParents($sourceArr,$newID, $arrParents);
				}
			}
		}
	}
	
	function recursiveUL($menu, $parents = 0, &$newMenu){	
		if(count($menu)>0){
			$idUL = 'ulGroup_' . $parents;
			$newMenu .= '<ul id="' . $idUL . '" >';
			foreach ($menu as $key => $val){
				$i	= self::counAppear($val['id'], $menu);
				$name = $val['name'];
				if($val['parents'] == $parents){
					$liMenu = 'liMenu_' . $val['id'];
					$arrUrl = array(
		                     			'module'=>'default',
		                     			'controller'=>'index',
		                     			'action'=>'product-category',
		                     			'id'=>$val['id'],
		                     			'title'=>$this->_filter->filter($name)
		                     			);
		            $lnkMenu = $this->_cmsUrl->cmsUrl($arrUrl, 'product-category');
		            
		            $name = str_replace('&', '&amp;', $name);
					$newMenu .= '<li id="'. $liMenu . '"><a href="' . $lnkMenu . '">' . $name . '</a>';
					unset($menu[$key]);
					$this->recursiveUL($menu, $val['id'], $newMenu);
					$newMenu .= '</li>';
				}
			}
			$newMenu .= '</ul>';
		}
	}
	
	public function counAppear($value = null, $arrays = null){
		$i = 0;
		if(count($arrays)> 0){
			foreach($arrays as $k => $v){
				if(array_search($value, $v)){
					$i++;
				}
			}
		}
		return $i;
	}
}